import json
import requests
import sys
from pathlib import Path

def test_bulk_registration():
    # API endpoint (注意末尾的斜杠)
    register_url = 'http://127.0.0.1:8000/api/users/register/'
    
    # 首先获取 CSRF token
    try:
        session = requests.Session()
        response = session.get('http://127.0.0.1:8000/api/users/')
        csrf_token = session.cookies.get('csrftoken')
        if not csrf_token:
            print("警告: 无法获取 CSRF token")
            csrf_token = 'dummy-token'
    except requests.exceptions.RequestException as e:
        print(f"警告: 获取 CSRF token 失败: {str(e)}")
        csrf_token = 'dummy-token'
    
    # 获取测试数据文件的绝对路径
    current_dir = Path(__file__).parent
    test_data_file = current_dir / 'test_users.json'
    
    # 读取测试用户数据
    try:
        with open(test_data_file, 'r', encoding='utf-8') as f:
            users_data = json.load(f)
    except FileNotFoundError:
        print(f"错误: 测试数据文件 {test_data_file} 不存在")
        sys.exit(1)
    
    # 批量注册用户
    success_count = 0
    failed_count = 0
    
    # 设置请求头
    headers = {
        'accept': 'application/json',
        'Content-Type': 'application/json',
        'X-CSRFToken': csrf_token
    }
    
    for user_data in users_data:
        # 添加测试验证码
        user_data['captcha'] = '123456'
        
        try:
            # 发送注册请求
            print(f"\n正在注册用户: {user_data['username']}")
            print(f"请求数据: {json.dumps(user_data, ensure_ascii=False)}")
            
            response = session.post(
                register_url,
                json=user_data,
                headers=headers
            )
            
            # 检查响应
            print(f"响应状态码: {response.status_code}")
            print(f"响应内容: {response.text}")
            
            if response.status_code == 201:
                print(f"✓ 用户 {user_data['username']} 注册成功")
                success_count += 1
            else:
                print(f"✗ 用户 {user_data['username']} 注册失败")
                try:
                    error_detail = response.json()
                    print(f"错误详情: {json.dumps(error_detail, ensure_ascii=False, indent=2)}")
                except json.JSONDecodeError:
                    print(f"原始错误信息: {response.text}")
                failed_count += 1
                
        except requests.exceptions.RequestException as e:
            print(f"✗ 请求错误: {str(e)}")
            failed_count += 1
            
        print("-" * 50)
    
    # 打印测试结果总结
    print("\n测试结果总结:")
    print(f"总计测试用户: {len(users_data)}")
    print(f"成功注册: {success_count}")
    print(f"注册失败: {failed_count}")

if __name__ == '__main__':
    print("开始测试用户批量注册...")
    print("-" * 50)
    test_bulk_registration()